<?php

namespace app\admin\controller\vppz;

use app\common\controller\Backend;
//use think\addons\Service;
//use think\Exception;
use think\Session;

use \app\admin\model\vppz\ExaminationOrderDetail as ExaminationOrderDetailModel;
use app\admin\model\vppz\App;


/**
 * 系统配置
 *
 * @icon fa fa-gears
 */
class PhysicalExamOrder extends Base
{
	protected $branch = 0;	// 0：插件市场版，1：自主授权版

    protected $model = null;

   protected $searchFields = ['id','name'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\ExaminationOrder;
        $this->hospitalModel = new \app\admin\model\vppz\Hospital;
        $this->ExaminationOrderDetailModel = new ExaminationOrderDetailModel;
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $admin = Session::get("admin");
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $listmodel = $this->model
                    ->where($where);
            $searchWhere =[];
            if($admin['is_pingtai'] != 1){
                $hospital = $this->hospitalModel->where(['admin_id'=>$admin['id']])->find();
                if(empty($hospital) === FALSE){
                    $searchWhere = ['hexiao_hospital_id'=>$hospital->id];
                    $listmodel = $listmodel->where($searchWhere);
                }else{
                    $searchWhere = ['hexiao_hospital_id'=>0];
                    $listmodel = $listmodel->where($searchWhere)->where('status','>',2);
                }
            }
            $list = $listmodel->order($sort, $order)
                    ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

  /**
     * 订单详情页
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $order = $row->toArray();
        if (!$order) {
            $this->error('订单不存在');
        }
        // 获取订单项目明细
        $items = $this->ExaminationOrderDetailModel::where('order_id', $ids)->select();
        $this->view->assign('order',$order);
        $this->view->assign('items',$items);
        $this->view->assign('mediaTypes',[
                ['value' => 'image', 'text' => '图片'],
                ['value' => 'pdf', 'text' => 'PDF文档']
            ]);
        return $this->view->fetch();
    }

    /**
     * 上传项目报告
     */
     public function uploadReport()
    {
        $request = $this->request;

        // 1. 接收并验证参数
        $itemId = $request->param('item_id', 0, 'intval');
        $type = $request->param('type', '', 'trim');

        if (empty($itemId)) {
            $this->error('项目ID不能为空');
        }
        if (!in_array($type, ['image', 'pdf'])) {
            $this->error('报告类型无效（仅支持image/pdf）');
        }

        // 2. 验证项目是否存在
        $item = $this->ExaminationOrderDetailModel::find($itemId);
        if (!$item) {
            $this->error('体检项目不存在或已删除');
        }

        // 3. 获取并验证上传文件
        $file = $request->file('file');
        if (!$file) {
            $this->error('请选择要上传的文件');
        }

        // 4. 配置文件校验规则（与前端完全一致）
        $allowExt = $type == 'image' ? ['jpg', 'jpeg', 'png', 'gif'] : ['pdf'];
        $maxSize = 10 * 1024 * 1024; // 10MB（单位：字节），与前端保持一致
        $savePath = 'uploads/report/' . date('Ymd'); // 保存路径：按日期分目录

        // 5. 自动创建上传目录（避免目录不存在报错）
        $rootPath = ROOT_PATH.'/public/' . $savePath;
        if (!file_exists($rootPath)) {
            mkdir($rootPath, 0755, true); // 递归创建目录，权限755（Linux兼容）
        }

        // 6. 执行文件校验与保存
        $info = $file->validate([
            'ext' => implode(',', $allowExt), // 允许的扩展名
            'size' => $maxSize // 最大文件大小
        ])->move($rootPath);

        if ($info) {
            // 7. 保存文件信息到数据库
            $fileSaveName = $info->getSaveName(); // 相对路径（如 20250820/abc123.jpg）
            $fullUrl = '/' . $savePath . '/' . $fileSaveName; // 完整访问URL（适配FastAdmin静态资源路径）

            $item->report_url = $fullUrl;
            $item->report_type = $type;
            $item->report_time = time();
            $item->save();

            $orderinfo = $this->model->where('id',$item->order_id)->find();
            $detail = $this->ExaminationOrderDetailModel->where([
                'order_id'=>$item->order_id
            ])->whereNull('report_url')->find();
            //通知
            $AppModel = new \app\admin\model\vppz\App();
                $app = $AppModel->find(1);
                $appid = $app['wxapp_id'];
                $secret = $app['wxapp_secret'];
                if (empty($this->object)) {
                    $this->object = new \Wxchat($appid, $secret);
                }
                $accessToken = $this->object->getaccesstoken();
                if (empty($orderinfo->openid) === FALSE) {
                        $send_data = array(
                            "thing1" => array(
                                "value" => $orderinfo->exam_person_name
                            ),
                            "time2" => array(
                                "value" => $orderinfo->exam_date
                            ),
                            "time3" => array(
                                "value" => date('Y-m-d H:i:s',$item->report_time)
                            ),
                            "phrase4" => array(
                                "value" => '报告已生成，请打开小程序查看'
                            )
                        );
                        \Wxchat::sendtmpldetail($orderinfo->openid, 'tF3JZheCj1qEyZq5rwHr81CvuJQOd_yiL6Lbuj_qV2Q', $accessToken, $send_data);
                    }
            if(empty($detail)){
                $this->model->where('id',$item->order_id)->update(array(
                    'status'=>4,
                    'updatetime'=>time()
                ));
            }

            // 8. 返回成功结果（前端需要url和type参数）
            $this->success('报告上传成功', '', [
                'url' => $fullUrl,
                'type' => $type,
                'file_name' => $info->getFilename() // 可选：返回保存后的文件名
            ]);
        } else {
            // 9. 返回具体错误信息（文件校验失败）
            $this->error('文件上传失败：' . $file->getError());
        }
    }

    /**
     * 删除项目报告
     */
    public function deleteReport($item_id)
    {
        $item = $this->ExaminationOrderDetailModel::find($item_id);
        if (!$item || !$item->report_url) {
            $this->error('报告不存在');
        }

        // 删除文件
        if (file_exists(ROOT_PATH . 'public' . $item->report_url)) {
            @unlink(ROOT_PATH . 'public' . $item->report_url);
        }

        // 清空数据库记录
        $item->report_url = '';
        $item->report_type = '';
        $item->report_time = null;
        $item->save();
        $this->model->where('id',$item->order_id)->update(array(
            'status'=>3,
            'updatetime'=>time()
        ));
        $this->success('删除成功','',[]);
    }

}
